"""
author: liuxu
date: 2025/9/17
description: 此模块用于测试--cl-trace功能
"""
import allure
import pytest
import re
from common.logger_ctrl import mylogger
from common.ssh_command import exec_cmd
from base_public.testbase import BasePublic
from setting import CPP_DIR, EXE_DIR

@allure.feature('opencl tracing指令')
@pytest.mark.high
class TestOpenclTrace(BasePublic):
    """测试opencl trace功能"""
    def test_opencl_trace(self, test_env):
        """
        测试矩阵转置程序
        :param test_env:
        :return:
        """
        # 编译待测用例
        exe_path = self.compile_source_code(compiler="clang++",
                                            src_file_name="OpenclCase/cl_MatrixTranspose.cpp",
                                            compile_paras="-lOpenCL -lpthread")

        # 执行测试命令
        ret, output = exec_cmd(f"hipprof --cl-trace {exe_path}", cwd=test_env)
        assert ret is True
        #TODO编写解析opencl trace文件的公共方法

    def test_opencl_trace_multithread_multidevice(self, test_env):
        """
        测试多线程多卡程序
        :param test_env:
        :return:
        """
        # 编译待测用例
        exe_path = self.compile_source_code(compiler="clang++",
                                            src_file_name="OpenclCase/cl_MatrixTranspose_thread_multi_device.cpp",
                                            compile_paras="-lamdocl64 -lpthread -lOpenCL")

        # 执行测试命令
        ret, output = exec_cmd(f"hipprof --cl-trace --trace-args --libc-trace --hsa-trace {exe_path}", cwd=test_env, timeout=60)
        assert ret is True

    def test_opencl_trace_from_db(self, test_env):
        """
        测试从db导出opencl的json数据
        :param test_env:
        :return:
        """
        # 编译待测用例
        exe_path = self.compile_source_code(compiler="clang++",
                                            src_file_name="OpenclCase/cl_MatrixTranspose_process.cpp",
                                            compile_paras="-lamdocl64 -lpthread -lOpenCL")

        # 执行测试命令
        ret0, output0 = exec_cmd(f"hipprof --cl-trace --trace-args {exe_path}", cwd=test_env)
        assert ret0 is True

        # 获取生成的db文件名
        pid = self.get_prof_pid(output0)
        db_name = f"hip-prof-{pid}.db"

        ret1, output1 = exec_cmd(f"hipprof --cl-trace --trace-args --print-trace --index-range 15:20 --db {db_name}", cwd=test_env)
        assert ret1 is True

        assert "clBuildProgram" in output1  # 判断打印api trace
        assert "COPY:" in output1 and "OPS :" in output1  # 判断打印tarce evect